package com.jtny.nytb.equipment.config;

import cn.hutool.core.util.ObjectUtil;
import com.jtny.component.dto.CurrentUserDTO;
import com.jtny.component.entity.LocalHolder;
import com.jtny.nytb.equipment.utils.ThreadLocalUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @author 智慧能源中心 - 伍天宇
 * @package com.jtny.nytb.energymonitor.config
 * @fileName FeginConfig.java
 * @createTime 2023年10月20日 16:32
 * @Copyright© 2023 jtny
 * 江投能源技术研究院 版权所有
 */
@Configuration
@ConditionalOnClass(RequestInterceptor.class)
public class FeignConfig implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        CurrentUserDTO currentUserDTO = LocalHolder.getCurrentUser();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        // 异步接口处理
        if (ObjectUtil.isEmpty(attributes)) {
            String tenantCode = ThreadLocalUtils.getTenantCode();
            requestTemplate.header("tenantCode", tenantCode);
            return;
        }
        assert attributes != null;
        HttpServletRequest request = attributes.getRequest();
        Enumeration<String> headerNames = request.getHeaderNames();
        //额外添加租户的code请求头
        if (ObjectUtil.isNotNull(ThreadLocalUtils.getTenantCode())){
            String tenantCode = ThreadLocalUtils.getTenantCode();
            requestTemplate.header("tenantCode", tenantCode);
            return;
        }
        requestTemplate.header("tenantCode", currentUserDTO.getTenantId());
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String name = headerNames.nextElement();
                String values = request.getHeader(name);
                // 跳过 content-length
                if (name.equals("content-length")) {
                    continue;
                }
                requestTemplate.header(name, values);
            }
        }
    }
}
